<template>
  <a-spin tip="正在加载...." :spinning="spinning">
    <div class="main">
      <div class="mianColor">
        <div class="top classificationTile">
          <div>常规警情统计报告预览</div>
          <div>
            <a-checkbox style="margin-right: 20px" v-model:checked="checkedbox">
              加载图表
            </a-checkbox>
            <a-button type="primary" @click="saveImgClick()">报告导出</a-button>
          </div>
        </div>
        <div class="report">
          <div style="text-align: center" class="sTypeface smallOne">
            {{ previewList.authXqdwName }}警情情况通报
            <br />
            <br />
            【{{ previewList.year }}】第{{ previewList.month }}期
          </div>
          <br />
          <br />
          <div class="zhDate numberThree">
            <div>{{ previewList.authXqdwNames }}编</div>
            <div>{{ previewList.exportData }}</div>
          </div>
          <br />
          <div class="fTypeface numberThree">
            &emsp;&emsp;
            {{ previewList.dateRange }}, {{ previewList.authXqdwName }}110{{
              crumbsDataName == '全部' ? '共计' : '“' + crumbsDataName + '”'
            }}
            <span v-if="topContent">
              接警{{ topContent.count }}起，{{
                thJudge(topContent.chainPercent, topContent.yoyPercent)
              }}，有效警情{{ topContent.yxjqTJ }}起，{{
                thJudge(topContent.yxChainPercent, topContent.yxYoyPercent)
              }}；其中，
              <span v-for="(item, index) in previewList.jurisdiction.slice(0, 2)">
                {{ item.name + item.caseNum + '起'
                }}{{ index + 1 == previewList.jurisdiction.slice(0, 2).length ? '。' : '，' }}
              </span>
            </span>
          </div>
          <div v-if="checkedbox">
            <div class="fTypeface numberThree">&emsp;&emsp; 下面分别是警情趋势图和分类统计图。</div>
            <div style="text-align: center" class="kTypeface numberThree">
              警情趋势图（{{ crumbsDataName }}）
            </div>
            <a-card class="setClass" style="height: 100%" size="small">
              <template #title>
                <img
                  src="@/assets/image/statistics/jie.svg"
                  v-show="apiType == 'jq' ? true : false"
                  alt=""
                  class="iconImage"
                />
                <img
                  src="@/assets/image/statistics/fan.svg"
                  v-show="apiType == 'fq' ? true : false"
                  alt=""
                  class="iconImage"
                />
                <div style="display: flex; align-items: center">
                  <span class="cardname">{{ `【 ${crumbsDataName} 】` }}警情趋势</span>
                  <div class="echartinfo" v-if="echartInfoData[0]?.name || echartInfoData[1]?.name">
                    <span>
                      <span v-if="echartInfoData[0]?.seriesName == '当前警情'">
                        {{ echartInfoData[0].name }} 当前警情
                        <span style="text-decoration: underline">
                          {{ echartInfoData[0].data }}
                        </span>
                      </span>
                      <span v-if="echartInfoData[0]?.seriesName == '去年同期'">
                        去年警情
                        <span style="text-decoration: underline">
                          {{ echartInfoData[0].data }}
                        </span>
                      </span>
                      &nbsp;
                      <span v-if="echartInfoData[1]?.seriesName == '去年同期'">
                        去年警情
                        <span style="text-decoration: underline">
                          {{ echartInfoData[1].data }}
                        </span>
                      </span>
                      &nbsp; 同比:{{ ecahrtinfo.percent }} &nbsp; &nbsp; 环比：{{
                        ecahrtinfo.hPercent
                      }}
                    </span>
                    <br />
                    <span
                      v-for="(item, index) in top3InfoList"
                      :key="index"
                      style="margin-right: 10px"
                    >
                      <span v-show="item.caseNum">
                        {{ item.xqdwName }} {{ item.caseNum }}
                        <span v-if="echartInfoData[0].data !== 0 ? true : false">
                          ({{ divide(item.caseNum, echartInfoData[0].data) }})
                        </span>
                      </span>
                    </span>
                  </div>
                </div>
              </template>
              <timeline-chart
                heightType="%"
                currentTheme="light"
                :data="trendList.dataList"
                height="300"
                :type="type"
                @Leave="handleLeave"
                :legend="['当前警情', '去年同期']"
                :fieldNames="{ name: 'dataDate', values: ['caseNum', 'yoyCaseNum'] }"
                v-if="trendList && trendList.dataList"
                @handleMove="handelEachartMove"
              />
              <a-empty v-else style="margin-top: 7%" />
            </a-card>
            <div style="text-align: center" class="kTypeface numberThree">
              分类统计图（{{ crumbsDataName }}）
            </div>
            <a-card class="setClass" :span="20" style="height: 100%" size="small">
              <template #title>
                <img
                  src="@/assets/image/statistics/jie.svg"
                  v-show="apiType == 'jq' ? true : false"
                  alt=""
                  class="iconImage"
                />
                <img
                  src="@/assets/image/statistics/fan.svg"
                  v-show="apiType == 'fq' ? true : false"
                  alt=""
                  class="iconImage"
                />
                <span class="cardname">{{ `【 ${crumbsDataName} 】` }}警情分类统计</span>
              </template>
              <barEcharts style="height: 300px" :option="barData" v-if="barData.xData.length" />
              <a-empty v-else style="margin-top: 5%" />
            </a-card>
          </div>
          <div v-if="previewList.jurisdiction.length" class="fTypeface numberThree">
            &emsp;&emsp;具体警情情况如下：
          </div>
          <div v-for="(item, index) in previewList.jurisdiction" :key="index">
            <div class="sTypeface numberThree">
              &emsp;&emsp;（{{ chinList[index] }}） {{ item.name }}
            </div>
            <div class="fTypeface numberThree">
              &emsp;&emsp;当期，共接{{
                item.name + item.caseNum + '起，' + item.contentValue
              }}；其中，
              <span v-for="(chi, chindex) in jurisdictionList.ayDataList[index]?.xjTopList">
                {{ chi.name + chi.count }}起，{{ thJudge(chi.chainPercent, chi.yoyPercent)
                }}{{
                  jurisdictionList.ayDataList[index]?.xjTopList.length == chindex + 1 ? '。' : '；'
                }}
              </span>
            </div>
            <div v-if="checkedbox">
              <div style="text-align: center" class="kTypeface numberThree">
                警情趋势图（{{ item.name }}）
              </div>
              <a-card class="setClass" style="height: 100%" size="small">
                <template #title>
                  <img
                    src="@/assets/image/statistics/jie.svg"
                    v-show="apiType == 'jq' ? true : false"
                    alt=""
                    class="iconImage"
                  />
                  <img
                    src="@/assets/image/statistics/fan.svg"
                    v-show="apiType == 'fq' ? true : false"
                    alt=""
                    class="iconImage"
                  />
                  <div style="display: flex; align-items: center">
                    <span class="cardname">{{ `【 ${item.name} 】` }}警情趋势1</span>
                    <div
                      class="echartinfo"
                      v-if="echartInfoData[0]?.name || echartInfoData[1]?.name"
                    >
                      <span>
                        <span v-if="echartInfoData[0]?.seriesName == '当前警情'">
                          {{ echartInfoData[0].name }} 当前警情
                          <span style="text-decoration: underline">
                            {{ echartInfoData[0].data }}
                          </span>
                        </span>
                        <span v-if="echartInfoData[0]?.seriesName == '去年同期'">
                          去年警情
                          <span style="text-decoration: underline">
                            {{ echartInfoData[0].data }}
                          </span>
                        </span>
                        &nbsp;
                        <span v-if="echartInfoData[1]?.seriesName == '去年同期'">
                          去年警情
                          <span style="text-decoration: underline">
                            {{ echartInfoData[1].data }}
                          </span>
                        </span>
                        &nbsp; 同比:{{ ecahrtinfo.percent }} &nbsp; &nbsp; 环比：{{
                          ecahrtinfo.hPercent
                        }}
                      </span>
                      <br />
                      <span
                        v-for="(item, index) in top3InfoList"
                        :key="index"
                        style="margin-right: 10px"
                      >
                        <span v-show="item.caseNum">
                          {{ item.xqdwName }} {{ item.caseNum }}
                          <span v-if="echartInfoData[0].data !== 0 ? true : false">
                            ({{ divide(item.caseNum, echartInfoData[0].data) }})
                          </span>
                        </span>
                      </span>
                    </div>
                  </div>
                </template>
                <timeline-chart
                  v-if="jurisdictionList.trendList[index]?.dataList"
                  heightType="%"
                  currentTheme="light"
                  :data="jurisdictionList.trendList[index]?.dataList"
                  height="300"
                  :type="type"
                  @Leave="handleLeave"
                  :legend="['当前警情', '去年同期']"
                  :fieldNames="{ name: 'dataDate', values: ['caseNum', 'yoyCaseNum'] }"
                  @handleMove="handelEachartMove"
                />
                <a-empty v-else style="margin-top: 7%" />
              </a-card>
              <div style="text-align: center" class="kTypeface numberThree">
                分类统计图（{{ item.name }}）
              </div>
              <a-card class="setClass" :span="20" style="height: 100%" size="small">
                <template #title>
                  <img
                    src="@/assets/image/statistics/jie.svg"
                    v-show="apiType == 'jq' ? true : false"
                    alt=""
                    class="iconImage"
                  />
                  <img
                    src="@/assets/image/statistics/fan.svg"
                    v-show="apiType == 'fq' ? true : false"
                    alt=""
                    class="iconImage"
                  />
                  <span class="cardname">{{ `【 ${item.name} 】` }}警情分类统计</span>
                </template>
                <barEcharts
                  v-if="jurisdictionList.barDataList[index]"
                  style="height: 300px"
                  :option="jurisdictionList.barDataList[index]"
                />
              </a-card>
              <div style="text-align: center" class="kTypeface numberThree">
                辖区分布图（{{ item.name }}）
              </div>
            </div>
            <div class="fTypeface numberThree">
              &emsp;&emsp;{{ item.name }}高发辖区依次为：
              <span v-for="(item, juindex) in jurisdictionList.pieData[index]?.slice(0, 3)">
                {{ item.name + item.caseNum }}起，占比{{ item.percent }}%{{
                  jurisdictionList.pieData[index].slice(0, 3).length == juindex + 1 ? '。' : '；'
                }}
              </span>
            </div>
            <a-card
              v-if="checkedbox"
              style="height: 100%; overflow: hidden"
              size="small"
              class="setClass"
            >
              <template #title>
                <img
                  src="@/assets/image/statistics/jie.svg"
                  v-show="apiType == 'jq' ? true : false"
                  alt=""
                  class="iconImage"
                />
                <img
                  src="@/assets/image/statistics/fan.svg"
                  v-show="apiType == 'fq' ? true : false"
                  alt=""
                  class="iconImage"
                />
                <span class="cardname">{{ `【 ${item.name} 】` }}辖区警情统计</span>
              </template>
              <pie
                currentTheme="light"
                :data="jurisdictionList.pieData[index]"
                height="300"
                heightType="%"
                :fieldNames="{
                  name: 'name',
                  value: 'caseNum',
                }"
                v-if="jurisdictionList.pieData[index]"
              />
              <a-empty v-else style="margin-top: 12%" />
            </a-card>
            <div>
              <div style="text-align: center" class="fTypeface numberThree">
                辖区单位下级案由TOP3对比表
              </div>
              <table class="tabrc">
                <tr v-if="jurisdictionList.xqData[index]">
                  <th>序号</th>
                  <th>辖区单位</th>
                  <th>{{ item.name }}</th>
                  <th>占比</th>
                  <th v-for="item in xqtitle(jurisdictionList.ayDataList[index]?.xjTopList)">
                    {{ item.name }}
                  </th>
                </tr>
                <tr v-for="(item, juindex) in jurisdictionList.pieData[index]">
                  <td>{{ juindex + 1 }}</td>
                  <td>{{ item.name }}</td>
                  <td>{{ item.caseNum }}</td>
                  <td>{{ item.percent }}%</td>
                  <td
                    v-for="ayitem in xqTop(jurisdictionList?.ayDataList[index]?.xqTopList[juindex])"
                  >
                    {{ ayitem.caseNum }}
                  </td>
                </tr>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </a-spin>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, reactive, computed, createVNode } from 'vue';
import moment from 'moment';
// import { BrokenLineItem } from '../../district-monitoring/jurisdiction-list/typing';
import TimelineChart from './components/line.vue';
import trendView from '../../district-monitoring/jurisdiction-list/js/trend-view';
// import nodata from '../../intelligent-analysis/alert-list/components/nodata.vue';
import barEcharts from './components/barEcharts.vue';
import { TreeSelect, message } from 'ant-design-vue';
// import list from '../components/police-list-drawer/index.vue';
// import rollTabs from '@/components/rollTabs/index.vue';
import { debounce, isNil } from 'lodash-es';
// import querySelect from './components/select.vue';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
import {
  queryXqdwList,
  queryFirstStat,
  queryStackChart,
  deaqueryVaryTrend,
  deaqueryXqdwPieChart,
  queryXqdwDealTop3,
  queryTime,
  queryXqdwCallTop3,
  queryStackChartel,
  deaqueryVaryTrendel,
  deaqueryXqdwPieChartel,
  queryFirstStatel,
  getExportXqWord,
  postJsonDownload,
  getQueryAll,
} from '@/api/intelligentanalysis/alert';
// import PoliceListDrawer from '../components/police-list-drawer/index.vue';
import Pie from '@/components/charts/pie/simple-pie/index.vue';
// import enlarge from '@/components/enlarge/index.vue';
import { omit } from 'lodash';
import { useStore } from 'vuex';
// import pickers from '@/components/s-picker/picker.vue';
import {
  querybarCharts,
  queryLowerAy,
  handlequeryVary,
  thJudge,
  xqPieChart,
  quantity,
  xqdwClassify,
  xqTop,
  xqtitle,
} from '@/views/routine-analysis/typing';
import { cloneDeep } from 'lodash';
import { Modal } from 'ant-design-vue';
import html2canvas from 'html2canvas';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';

//查询条件
interface queryForm {
  callTimeStart: any;
  callTimeEnd: any;
  xqdwCodes: string; //指挥中心
  classifyCodes: string; //专题
  otherFlag: string | 'N' | 'Y'; //其他
  trafficFlag: string | 'N' | 'Y'; // 交通
  dealSummaryCodes?: string;
  callSummaryCodes?: string;
}
//导航栏数据格式
interface navType {
  all: any;
  list: any;
}
export default defineComponent({
  components: {
    TimelineChart,
    // nodata,
    barEcharts,
    Pie,
    // list,
    // PoliceListDrawer,
    // enlarge,
    // rollTabs,
    // querySelect,
    // pickers,
  },
  setup() {
    const store = useStore();
    const tabsIndex = ref<number>(0);
    const type = ref<any>('传统');
    const apiType = ref<string>(JSON.parse(localStorage.getItem('queryForm') as any).apiType);
    const checked = ref<boolean>(true);
    const height = ref<number>(88);
    const timelineHeight = ref<number>(19);
    const drawerName = ref<any>('');
    const visible = ref<any>(false);
    const params = ref<any>([]);
    const portionUrl = ref<any>('');
    const policeTabs = ref<Array<any>>([]);
    const tabVisible = ref<boolean>(false);
    const uploading = ref<boolean>(false);
    const classificationData = ref<any>([]);
    const urlFile = (window as any).g.baseURL;
    const dropdownStyle = ref<any>({
      height: '330px',
      width: '350px',
      overflow: 'auto',
    });
    const defaultValue = ref('');
    const queryClass = ref<string | undefined>(undefined);
    const handleQuery = () => {
      if (treecrumbs.value.length) {
        crumbsData.value = treecrumbs.value;
      }
      activeIndex.value = crumbsData.value[0].vcode;
      query();
    };
    let index = ref<number>(0);
    const spinning = ref<boolean>(false);
    const checkedbox = ref<boolean>(true);
    let count = ref<number>(0);
    const activeIndex = ref<string>('');
    const trendList = ref<any>();
    trendList.value = trendView.RESULT;
    //用于判断智能 传统切换
    const flag = ref<string>('b');
    //指挥中心数据
    const treeData = ref<Array<any>>([]);
    const authXqdwName = ref<string>(store.getters[`user/info`].authXqdwName);
    const chinList = ['一', '二', '三', '四', '五'];

    const handlequeryXqdwList = () => {
      return new Promise(function (resolve, reject) {
        queryXqdwList({}).then(res => {
          if (res.code === 200 && res.data) {
            resolve(res.data); //在异步操作成功时调
          } else {
            reject(res); //在异步操作失败时调用
          }
        });
      });
    };
    const handletRee = () => {
      store.dispatch(`dictionary/GET_TREE_PARAM`).then(() => {
        classificationData.value = computed(() => store.getters['dictionary/callTree']).value;
      });
    };
    //查询分类change事件
    const treecrumbs = ref<any>([]);
    const treeChange = (value, label, extra) => {
      treecrumbs.value = [];
      let arr = ref<any>(extra.triggerNode);
      if (arr.value.value) {
        treecrumbs.value.push({ vcode: arr.value.value, name: arr.value.title });
        if (arr.value.vcTreeNode.value) {
          treeChildren(arr.value.vcTreeNode);
        }
      }
      queryForm.dealSummaryCodes = apiType.value == 'fq' ? value : '';
      queryForm.callSummaryCodes = apiType.value == 'jq' ? value : '';
    };
    const treeChildren = value => {
      treecrumbs.value.unshift({ vcode: value.value, name: value.title });
      if (value.vcTreeNode.value) {
        treeChildren(value.vcTreeNode);
      }
    };
    //获取时间
    const handlequeryTime = () => {
      return new Promise(function (resolve, reject) {
        queryTime({ module: 'ZNFX' }).then(res => {
          if (res.code === 200) {
            resolve(res.data); //在异步操作成功时调
          } else {
            reject(res); //在异步操作失败时调用
          }
        });
      });
    };
    //日期查询条件
    const date = ref<any>([]);

    //查询字段
    let queryForm: queryForm = reactive(
      JSON.parse(localStorage.getItem('queryForm') as any).queryForm,
    );

    //预览数据
    const previewList = ref<any>({
      authXqdwName: authXqdwName,
      authXqdwNames: authXqdwName.value.indexOf('派出所') != -1 ? '综合指挥室' : '指挥中心',
      year: moment().format('YYYY'),
      month: moment().format('MM'),
      exportData: moment().format('YYYY年MM月DD日'),
      dateRange:
        moment(queryForm.callTimeStart).format('YYYY年MM月DD日HH时') +
        '至' +
        moment(queryForm.callTimeEnd).format('YYYY年MM月DD日HH时'),
      jurisdiction: JSON.parse(localStorage.getItem('queryForm') as any).jurisdiction,
    });

    let crumbsDataName = JSON.parse(localStorage.getItem('queryForm') as any).crumbsData;
    //智能 导航栏数据
    // const navData = ref<Array<any>>([]);
    const navData: navType = reactive({
      all: {},
      list: [],
    });
    // 获取专题分类
    const getSubjectData = () => {
      const params = {
        ...omit(queryForm, ['classifyCodes', 'dealSummaryCodes', 'callSummaryCodes']),
      };
      if (apiType.value == 'fq') {
        queryFirstStat(params).then(res => {
          navData.all = res.data.all;
          navData.list = res.data.list;
        });
      } else {
        queryFirstStatel(params).then(res => {
          navData.all = res.data.all;
          navData.list = res.data.list;
        });
      }
    };
    const handleAdd = () => {
      if (count.value == navData.list.length - 1) {
        count.value = 0;
      }
      if (count.value < navData.list.length) {
        count.value++;
      }
    };
    const handleDel = () => {
      if (count.value > 0) {
        count.value--;
      }
    };
    const content = ref<any>([]);
    //警情分类统计数据
    const barData = ref<any>({
      xData: [],
      yData: [],
      newData: [],
    });
    // 警情分类统计
    const querybarChart = () => {
      spinning.value = true;
      barData.value.yData = [];
      barData.value.xData = [];
      barData.value.newDara = [];
      let obj = ref<any>({
        name: '总数',
        type: 'bar',
        barGap: '-100%',
        barWidth: 30,
        label: {
          position: 'top',
          normal: {
            show: true, //显示数值
            position: 'top', // 在上方显示
            distance: 10, // 距离图形元素的距离。当 position 为字符描述值（如 'top'、'insideRight'）时候有效。
            verticalAlign: 'middle',
            // formatter: '{c}',
            textStyle: { color: '#000', fontSize: 12, textAline: 'center' }, //设置数值颜色
          },
        },
        itemStyle: {
          normal: {
            color: 'rgba(128, 128, 128, 0)', // 设置背景颜色为透明
          },
        },
        data: [],
      });

      obj.value.data = [];
      spinning.value = true;
      if (apiType.value == 'fq') {
        queryStackChart(queryForm)
          .then(res => {
            if (res.data.xList) {
              res.data.xList.forEach(item => {
                obj.value.data.push(item.caseNum);
                item.data = [];
                item.childCode = [];
                barData.value.xData.push(item.name);
                res.data.yList.forEach(el => {
                  if (el.code == item.code) {
                    el.name = el.childName;
                    el.parentName = item.parentName;
                    el.percent = item.percent;
                    el.caseNum = item.caseNum;
                    item.childCode.push(el.childCode);
                    el.code = item.code;
                    barData.value.yData.push(el);
                  }
                });
              });
              barData.value.newDara = res.data.xList;
              barData.value.yData = barData.value.yData.map(item => ({
                stack: 'value',
                type: 'bar',
                name: item.name,
                data: item.valueList,
                parentName: item.parentName,
                percent: item.percent,
                caseNum: item.caseNum,
                code: item.code,
                childCode: item.childCode,
                barWidth: '30',
              }));
              barData.value.yData.push(obj.value);
            }
          })
          .finally(() => {
            spinning.value = false;
          });
      } else {
        queryStackChartel(queryForm)
          .then(res => {
            if (res.data.xList) {
              res.data.xList.forEach(item => {
                obj.value.data.push(item.caseNum);
                item.data = [];
                item.childCode = [];
                barData.value.xData.push(item.name);
                res.data.yList.forEach(el => {
                  if (el.code == item.code) {
                    el.name = el.childName;
                    el.parentName = item.parentName;
                    el.percent = item.percent;
                    el.caseNum = item.caseNum;
                    item.childCode.push(el.childCode);
                    el.code = item.code;
                    barData.value.yData.push(el);
                  }
                });
              });
              barData.value.newDara = res.data.xList;
              barData.value.yData = barData.value.yData.map(item => ({
                stack: 'value',
                type: 'bar',
                name: item.name,
                data: item.valueList,
                parentName: item.parentName,
                percent: item.percent,
                caseNum: item.caseNum,
                topList: item.topList,
                code: item.code,
                childCode: item.childCode,
                barWidth: '30',
              }));
              barData.value.yData.push(obj.value);
              content.value = quantity(barData.value.newDara.slice(0, 6));
            }
          })
          .finally(() => {
            spinning.value = false;
          });
      }

      handlequeryVaryTrend();
      pieChart();
    };
    const crumbsData = ref<any>([{ name: '全部', vcode: '' }]);
    const clickEchart = debounce(function (value) {
      /***
       * 判断柱状图是否存在下级  不存在弹出list
       */
      if (barData.value?.newDara[value].childCode.length > 1) {
        crumbsData.value.push({
          name: barData.value.newDara[value].name,
          vcode: crumbsData.value.length == '0' ? '' : barData.value.newDara[value].code,
        });
        queryForm.dealSummaryCodes = apiType.value == 'fq' ? barData.value.newDara[value].code : '';
        queryForm.callSummaryCodes = apiType.value == 'jq' ? barData.value.newDara[value].code : '';
        querybarChart();
        handlequeryVaryTrend();
        queryXqdwClassify();
        pieChart();
      } else {
        portionUrl.value = '/aitype/caseInfo/queryCaseInfo';
        params.value = {
          dealSummaryCode: apiType.value == 'fq' ? barData.value.newDara[value].code : '',
          callSummaryCode: apiType.value == 'jq' ? barData.value.newDara[value].code : '',
          callTimeStart: queryForm.callTimeStart,
          callTimeEnd: queryForm.callTimeEnd,
          xqdwCodes: queryForm.xqdwCodes,
          page: 1,
          searchType: apiType.value == 'fq' ? '1' : '2',
          otherFlag: queryForm.otherFlag,
          trafficFlag: queryForm.trafficFlag,
          size: 10,
        };
        //弹框头部查询条件信息
        echartInfo.value = {
          type: apiType.value === 'fq' ? '反馈警情' : '接警警情',
          time: date.value[0] + ' 至 ' + date.value[1],
          name: crumbsData.value[crumbsData.value.length - 1].name,
        };
        visible.value = true;
      }
    }, 1000);
    //echart 回退
    const handleNav = (value, index) => {
      if (index == crumbsData.value.length - 1) {
        return;
      }
      queryForm.dealSummaryCodes = apiType.value == 'fq' ? value.vcode : '';
      queryForm.callSummaryCodes = apiType.value == 'jq' ? value.vcode : '';
      querybarChart();
      handlequeryVaryTrend();
      queryXqdwClassify();
      crumbsData.value = crumbsData.value.slice(0, index + 1);
    };
    //警情趋势预警数据
    //警情趋势预警数据查询
    const handlequeryVaryTrend = () => {
      if (apiType.value == 'fq') {
        deaqueryVaryTrend(queryForm).then(res => {
          trendList.value = res.data;
        });
      } else {
        deaqueryVaryTrendel(queryForm).then(res => {
          trendList.value = res.data;
        });
      }
    };
    // top3
    const topData = ref<Array<any>>([]);
    const queryXqdwClassify = () => {
      if (apiType.value == 'fq') {
        queryXqdwDealTop3(queryForm).then(res => {
          topData.value = res.data;
        });
      } else {
        queryXqdwCallTop3(queryForm).then(res => {
          topData.value = res.data;
        });
      }
    };
    //点击辖区单位
    const pieRenderClickHandle = (e: any) => {
      const dataIndex = e?.target?.dataIndex;
      if (!isNil(dataIndex)) {
        visible.value = true;
        portionUrl.value = '/aitype/caseInfo/queryCaseInfo';
        params.value = {
          dealSummaryCodes: apiType.value == 'fq' ? queryForm.dealSummaryCodes : '',
          callSummaryCodes: apiType.value == 'jq' ? queryForm.callSummaryCodes : '',
          xqdwCode: pieData.value[dataIndex].code,
          callTimeStart: queryForm.callTimeStart,
          callTimeEnd: queryForm.callTimeEnd,
          page: 1,
          searchType: apiType.value == 'fq' ? '1' : '2',
          otherFlag: queryForm.otherFlag,
          trafficFlag: queryForm.trafficFlag,
          size: 10,
        };
        echartInfo.value = {
          type: apiType.value === 'fq' ? '反馈警情' : '接警警情',
          time: date.value[0] + ' 至 ' + date.value[1],
          name: crumbsData.value[crumbsData.value.length - 1].name,
        };
      }
    };
    //日期
    const onChange = value => {
      date.value = value;
      queryForm.callTimeStart = value[0];
      queryForm.callTimeEnd = value[1];
    };
    const query = () => {
      getSubjectData();
      querybarChart();
      handlequeryVaryTrend();
      queryXqdwClassify();
      pieChart();
      //刷新组件
      tabsIndex.value++;
    };
    //其他
    const handleother = e => {
      if (e.target.checked) {
        queryForm.otherFlag = 'Y';
      } else {
        queryForm.otherFlag = 'N';
      }
      activeIndex.value = '';
      queryForm.callSummaryCodes = '';
      queryForm.dealSummaryCodes = '';
      date.value = originalDate.value;
      queryForm.callTimeStart = originalDate.value[0];
      queryForm.callTimeEnd = originalDate.value[1];
      queryForm.xqdwCodes = '';
      tabsIndex.value++;
      getSubjectData();
      handlePublic();
    };
    //交通
    const handletraffic = e => {
      if (e.target.checked) {
        queryForm.trafficFlag = 'Y';
      } else {
        queryForm.trafficFlag = 'N';
      }
      tabsIndex.value++;
      activeIndex.value = '';
      queryForm.callSummaryCodes = '';
      queryForm.dealSummaryCodes = '';
      date.value = originalDate.value;
      queryForm.callTimeStart = originalDate.value[0];
      queryForm.callTimeEnd = originalDate.value[1];
      queryForm.xqdwCodes = '';
      getSubjectData();
      handlePublic();
    };
    //点击专题搜索弹框
    const onCascader = (value, option) => {
      queryForm.classifyCodes = '';
      queryForm.dealSummaryCodes = apiType.value == 'fq' ? value[value.length - 1] : '';
      queryForm.callSummaryCodes = apiType.value == 'jq' ? value[value.length - 1] : '';
      activeIndex.value = number.value;
      crumbsData.value = optionValue.value;
      let newArr = option.map(item => ({
        name: item.name,
        vcode: item.code,
      }));
      crumbsData.value = crumbsData.value.concat(newArr);
      handlePublic();
    };
    //点击select
    const handleClick = (value, option) => {
      queryForm.classifyCodes = '';
      queryForm.dealSummaryCodes = apiType.value == 'fq' ? value : '';
      queryForm.callSummaryCodes = apiType.value == 'jq' ? value : '';
      activeIndex.value = number.value;
      crumbsData.value = optionValue.value;
      crumbsData.value = crumbsData.value.concat(option);
      queryClass.value = value;
      handlePublic();
    };
    let number = ref<any>('');
    const optionValue = ref<Array<any>>([]);
    const handleItem = value => {
      optionValue.value = [{ name: value.vname, vcode: value.vcode }];
      number.value = value.vcode;
    };
    //点击专题
    const handleSpecial = value => {
      crumbsData.value = [{ name: value.vname, vcode: value.vcode }];
      queryForm.classifyCodes = '';
      if (apiType.value == 'fq') {
        queryForm.dealSummaryCodes = value.vcode;
        queryForm.callSummaryCodes = '';
      } else {
        queryForm.dealSummaryCodes = '';
        queryForm.callSummaryCodes = value.vcode;
      }
      activeIndex.value = value.vcode;
      handlePublic();
    };
    //点击指挥中心
    const handleSelect = value => {
      queryForm.xqdwCodes = value.toString();
    };
    //辖区警情统计
    let pieData = ref<any>([]);
    const pieChart = () => {
      if (apiType.value == 'fq') {
        deaqueryXqdwPieChart(queryForm).then(res => {
          res.data.forEach(item => {
            item.value = item.caseNum;
          });
          pieData.value = res.data;
        });
      } else {
        deaqueryXqdwPieChartel(queryForm).then(res => {
          res.data.forEach(item => {
            item.value = item.caseNum;
          });
          // res.data.push({});
          pieData.value = res.data;
        });
      }
    };
    const lineParams = [
      {
        name: '当期警情',
        url: '/aitype/caseInfo/queryCaseInfo',
        params: reactive({
          dealSummaryCodes: apiType.value == 'fq' ? queryForm.dealSummaryCodes : '',
          callSummaryCodes: apiType.value == 'jq' ? queryForm.dealSummaryCodes : '',
          callTimeStart: '',
          callTimeEnd: '',
          page: 1,
          searchType: '1',
          otherFlag: queryForm.otherFlag,
          trafficFlag: queryForm.trafficFlag,
          xqdwCodes: queryForm.xqdwCodes,
          size: 10,
        }),
      },
      {
        name: '去年同期',
        url: '/aitype/caseInfo/queryCaseInfo',
        params: reactive({
          dealSummaryCodes: apiType.value == 'fq' ? queryForm.dealSummaryCodes : '',
          callSummaryCodes: apiType.value == 'jq' ? queryForm.dealSummaryCodes : '',
          callTimeStart: '2020-07-19 02:08:03',
          callTimeEnd: '2021-07-18 23:59:59',
          page: 1,
          size: 10,
          searchType: 1,
          otherFlag: queryForm.otherFlag,
          trafficFlag: queryForm.trafficFlag,
          xqdwCodes: queryForm.xqdwCodes,
        }),
      },
    ];
    const echartInfo = ref<any>({});
    //趋势图点击
    const chartClickLineEl = (index, item) => {
      tabVisible.value = true;
      drawerName.value = '警情趋势';
      lineParams[0].params.callTimeStart = `${item.dataDate} 00:00:00`;
      lineParams[0].params.callTimeEnd = `${item.dataDate} 23:59:59`;
      lineParams[0].params.xqdwCodes = queryForm.xqdwCodes;
      lineParams[1].params.xqdwCodes = queryForm.xqdwCodes;
      lineParams[0].params.trafficFlag = queryForm.trafficFlag;
      lineParams[0].params.otherFlag = queryForm.otherFlag;
      lineParams[1].params.trafficFlag = queryForm.trafficFlag;
      lineParams[1].params.otherFlag = queryForm.otherFlag;
      lineParams[0].params.searchType = apiType.value == 'fq' ? '1' : '2';
      lineParams[1].params.searchType = apiType.value == 'fq' ? '1' : '2';
      lineParams[0].params.dealSummaryCodes =
        apiType.value == 'fq' ? queryForm.dealSummaryCodes : '';
      lineParams[0].params.callSummaryCodes =
        apiType.value == 'jq' ? queryForm.callSummaryCodes : '';
      lineParams[1].params.callTimeStart = `${moment(item.dataDate)
        .subtract(1, 'years')
        .format('YYYY-MM-DD')} 00:00:00`;
      lineParams[1].params.callTimeEnd = `${moment(item.dataDate)
        .subtract(1, 'years')
        .format('YYYY-MM-DD')} 23:59:59`;
      lineParams[1].params.dealSummaryCodes =
        apiType.value == 'fq' ? queryForm.dealSummaryCodes : '';
      lineParams[1].params.callSummaryCodes =
        apiType.value == 'jq' ? queryForm.callSummaryCodes : '';
      policeTabs.value = lineParams;
      //弹框头部查询条件信息
      echartInfo.value = {
        time: echartInfoData.value[0].name,
        type: apiType.value === 'fq' ? '反馈警情' : '接警警情',
        name: crumbsData.value[crumbsData.value.length - 1].name,
      };
    };
    //请求接口
    const handlePublic = () => {
      querybarChart();
      handlequeryVaryTrend();
      queryXqdwClassify();
      pieChart();
    };

    const handleHeight = value => {
      height.value = value;
    };
    const handletimelineHeight = value => {
      timelineHeight.value = value;
    };
    //重置
    const handleResh = () => {
      location.reload();
    };
    //接警 反馈切换
    const handleTypeqh = e => {
      crumbsData.value = [{ name: '全部', vcode: '' }];
      apiType.value = e.target.value;
      if (apiType.value === 'fq') {
        store.dispatch(`dictionary/GET_TREE_PARAM`).then(() => {
          classificationData.value = computed(() => store.getters['dictionary/dealTree']).value;
        });
      } else {
        store.dispatch(`dictionary/GET_TREE_PARAM`).then(() => {
          classificationData.value = computed(() => store.getters['dictionary/callTree']).value;
        });
      }
      activeIndex.value = '';
      queryForm.callSummaryCodes = '';
      queryForm.dealSummaryCodes = '';
      queryClass.value = undefined;
      defaultValue.value = treeData.value[0]?.code || '';
      queryForm.xqdwCodes = defaultValue.value;
      getSubjectData();
      handlePublic();
      tabsIndex.value++;
    };

    const customRequest = () => {
      if (!queryForm.xqdwCodes || !queryForm.callTimeStart || !queryForm.callTimeEnd) {
        return message.warning('请填写辖区与日期范围！');
      }
      uploading.value = true;
      let obj = ref({});
      if (apiType.value == 'fq') {
        obj.value = {
          xqdwCode: queryForm.xqdwCodes,
          minDate: queryForm.callTimeStart,
          maxDate: queryForm.callTimeEnd,
          otherFlag: queryForm.otherFlag,
          trafficFlag: queryForm.trafficFlag,
          dealSummaryCode: queryForm.dealSummaryCodes,
        };
      } else if (apiType.value == 'jq') {
        obj.value = {
          xqdwCode: queryForm.xqdwCodes,
          minDate: queryForm.callTimeStart,
          maxDate: queryForm.callTimeEnd,
          otherFlag: queryForm.otherFlag,
          trafficFlag: queryForm.trafficFlag,
          callSummaryCode: queryForm.callSummaryCodes,
        };
      } else {
        obj.value = {
          xqdwCode: queryForm.xqdwCodes,
          minDate: queryForm.callTimeStart,
          maxDate: queryForm.callTimeEnd,
          otherFlag: queryForm.otherFlag,
          trafficFlag: queryForm.trafficFlag,
        };
      }
      getExportXqWord(obj.value)
        .then(res => {
          const resCode = ref<any>(res);
          if (resCode.value.code == 200) {
            window.location.href =
              urlFile + '/report/download' + '?id=' + resCode.value.data.fileName;
            message.success('报告导出成功！');
          } else {
            message.error('报告导出失败！');
          }
          uploading.value = false;
        })
        .catch(() => {
          uploading.value = false;
          message.error('报告导出失败！');
        });
    };
    const top3InfoList = ref<any>({});
    //echart鼠标移动
    let echartInfoData = ref<any>([]);
    let ecahrtinfo = ref<any>({});
    const handelEachartMove = value => {
      echartInfoData.value = value;
      let index = value[0].dataIndex;
      top3InfoList.value = trendList.value.dataList[index].top3List || [];
      ecahrtinfo.value = trendList.value.dataList[index];
    };
    //鼠标离开
    const handleLeave = value => {
      if (value) {
        echartInfoData.value = [];
      }
    };
    const originalDate = ref<Array<string>>([]);
    const flTopsList = ref<any>({});

    const divide = (num1, num2) => {
      let t1, t2, r1, r2;
      try {
        t1 = num1.toString().split('.')[1].length;
      } catch (e) {
        t1 = 0;
      }
      try {
        t2 = num2.toString().split('.')[1].length;
      } catch (e) {
        t2 = 0;
      }
      r1 = Number(num1.toString().replace('.', ''));
      r2 = Number(num2.toString().replace('.', ''));
      let number = (r1 / r2) * Math.pow(10, t2 - t1) * 100;
      return number.toFixed(2) + '%';
    };

    const jurisdictionList = ref<any>({
      barDataList: [],
      trendList: [],
      pieData: [],
      xqData: [],
      ayDataList: [],
    });
    const charts = async () => {
      const jurisdiction = JSON.parse(localStorage.getItem('queryForm') as any).jurisdiction;
      jurisdiction.forEach(el => {
        jurisdictionList.value.barDataList.push(
          querybarCharts(cloneDeep(queryForm), el.code, apiType.value),
        );
        queryLowerAy(cloneDeep(queryForm), el.code, el.level, apiType.value).then(res => {
          jurisdictionList.value.ayDataList.push(res);
        });
        handlequeryVary(cloneDeep(queryForm), el.code, apiType.value).then(res => {
          jurisdictionList.value.trendList.push(res);
        });
        xqPieChart(cloneDeep(queryForm), el.code, apiType.value).then(res => {
          jurisdictionList.value.pieData.push(res);
        });
        xqdwClassify(cloneDeep(queryForm), el.code, apiType.value).then(res => {
          jurisdictionList.value.xqData.push(res);
        });
      });
    };

    // 通过code获取警情
    const topContent = ref();
    const queryAll = async () => {
      const res = await getQueryAll(queryForm);
      if (res.code === 200) {
        topContent.value = res.data;
      }
    };

    const fileList = ref<any>([]);
    //报告导出
    const saveImgClick = () => {
      Modal.confirm({
        title: '提示',
        icon: createVNode(ExclamationCircleOutlined),
        content: '是否导出报告？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          spinning.value = true;
          setTimeout(() => {
            if (checkedbox.value) {
              saveImg();
            } else {
              exportWord();
            }
          }, 500);
        },
      });
    };

    const saveImg = () => {
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
      const naClass = ref<any>(document.getElementsByClassName('setClass'));
      for (let index = 0; index < naClass.value.length; index++) {
        var width = naClass.value[index].offsetWidth; //dom宽
        var height = naClass.value[index].offsetHeight; //dom高
        var scale = 2; //放大倍数 这个相当于清晰度 调大一点更清晰一点
        html2canvas(naClass.value[index], {
          width: width,
          height: height,
          backgroundColor: '#ffffff', //背景颜色 为null是透明
          scale: scale,
          x: 0,
          y: 0,
          scrollX: -3, //如果左边多个白边 设置该偏移-3 或者更多
          scrollY: 0,
          useCORS: true, //是否使用CORS从服务器加载图像 !!!
          allowTaint: true, //是否允许跨域图像污染画布  !!!
        }).then(canvas => {
          var url = canvas.toDataURL(); //这里上面不设值cors会报错
          fileList.value[index] = dataURLtoFile(url, new Date().getTime() + '.png');
          if (index + 1 == naClass.value.length) {
            exportWord();
          }
        });
      }
    };

    //base64转文件流
    function dataURLtoFile(base64File, filename) {
      var arr = base64File.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    }

    const exportWord = () => {
      const formData = new FormData();
      fileList.value.forEach(file => {
        formData.append('files[]', file);
      });
      formData.append('hasPicture', checkedbox.value as any);
      formData.append('xqdwCode', queryForm.xqdwCodes);
      formData.append('minDateTime', queryForm.callTimeStart);
      formData.append('maxDateTime', queryForm.callTimeEnd);
      apiType.value == 'fq'
        ? formData.append('dealSummaryCode', queryForm.dealSummaryCodes as any)
        : formData.append('callSummaryCode', queryForm.callSummaryCodes as any);
      postJsonDownload(urlFile + '/report/exportXqWord', formData).then(res => {
        const resCode = ref<any>(res);
        if (resCode.value.code == 200) {
          window.location.href =
            urlFile + '/report/download' + '?id=' + resCode.value.data.fileName;
          message.success('报告导出成功！');
        } else {
          message.error('报告导出失败！');
        }
        spinning.value = false;
      });
    };

    onMounted(() => {
      Promise.all([handlequeryTime(), handlequeryXqdwList()])
        .then(([reslut1, reslut2]: Array<any>) => {
          treeData.value = reslut2 || [];
          defaultValue.value = treeData.value[0]?.code || '';
          queryForm.xqdwCodes = defaultValue.value;
          queryForm.callTimeStart = reslut1.callTimeStart;
          queryForm.callTimeEnd = reslut1.callTimeEnd;
          date.value[0] = reslut1.callTimeStart;
          date.value[1] = reslut1.callTimeEnd;
          originalDate.value = date.value;
          if (reslut1.callTimeStart) {
            getSubjectData();
            querybarChart();
            handlequeryVaryTrend();
            queryXqdwClassify();
            pieChart();
          }
        })
        .catch(err => {
          console.log('err', err);
        });
      charts();
      queryAll();
      handletRee();
    });
    return {
      flTopsList,
      top3InfoList,
      ecahrtinfo,
      queryClass,
      originalDate,
      treecrumbs,
      handleLeave,
      echartInfoData,
      handelEachartMove,
      handletRee,
      handleTypeqh,
      classificationData,
      checked,
      handleResh,
      type,
      height,
      handletimelineHeight,
      handleHeight,
      timelineHeight,
      number,
      params,
      portionUrl,
      tabVisible,
      visible,
      pieRenderClickHandle,
      drawerName,
      policeTabs,
      chartClickLineEl,
      handleQuery,
      clickEchart,
      dropdownStyle,
      spinning,
      activeIndex,
      handlequeryVaryTrend,
      onChange,
      onCascader,
      handleItem,
      pieData,
      handleother,
      getSubjectData,
      SHOW_PARENT,
      moment,
      queryForm,
      navData,
      querybarChart,
      barData,
      date,
      treeData,
      handlequeryXqdwList,
      handleSelect,
      flag,
      trendList,
      queryXqdwClassify,
      handleAdd,
      count,
      handleDel,
      topData,
      handleSpecial,
      handlePublic,
      handletraffic,
      pieChart,
      index,
      crumbsData,
      handleNav,
      apiType,
      customRequest,
      uploading,
      defaultValue,
      tabsIndex,
      handleClick,
      treeChange,
      query,
      divide,
      echartInfo,
      previewList,
      crumbsDataName,
      querybarCharts,
      chinList,
      jurisdictionList,
      thJudge,
      content,
      checkedbox,
      saveImgClick,
      topContent,
      xqTop,
      xqtitle,
    };
  },
});
</script>

<style lang="less" scoped>
.main {
  width: 100%;
  color: #000 !important;
  background-color: #e6e6e6;
}
.mianColor {
  color: #000;
}
.report {
  width: 1200px;
  margin: 50px auto;
  padding: 100px;
  background-color: #fff;
}
//宋体
.sTypeface {
  font-weight: bold;
  font-family: '宋体';
}
//仿宋
.fTypeface {
  font-family: '仿宋';
}
//黑体
.hTypeface {
  font-family: '黑体';
}
//楷体
.kTypeface {
  font-weight: bold;
  font-family: '楷体';
}
//小一字体
.smallOne {
  font-size: 24px;
}
//小二字体
.smallTwo {
  font-size: 18px;
}
//三号字体
.numberThree {
  font-size: 16px;
}
.zhDate {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #000;
}
.top {
  width: 100%;
  height: 50px;
  padding: 0px 20px;
  color: #fff;
  background: #34363c;
}
.tabrc {
  width: 80%;
  margin: 0 auto;
  text-align: center;
  border: 1px solid #000;
  td {
    border: 1px solid #000;
  }
  th {
    background: #ccc;
    border: 1px solid #000;
  }
}
:deep(.ant-card-head) {
  padding: 0;
  color: #000;
  background: #fff;
  border: 1px solid #f0f0f0;
}
:deep(.ant-card-bordered) {
  border: 1px solid #f0f0f0;
}
:deep(.ant-card) {
  background: #fff;
}
.classificationTile {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.iconImage {
  position: absolute;
  top: -2px;
  left: -2px;
  width: 35px;
  height: 35px;
}
.cardname {
  margin-left: 20px;
  font-weight: 500;
  font-size: 16px;
  font-family: Source Han Sans CN;
}
.echartinfo {
  display: inline-block;
  display: table;
  width: 470px;
  margin: 0 auto;
  color: #000;
  font-weight: 500;
  font-size: 12px;
  font-family: Source Han Sans CN;
  text-align: left;
}
</style>
